/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * @author zhouqh
 * Date: 2010-7-1 下午05:58:21
 */
package com.ccxe.manage.filters;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhouqh
 * 
 */
public class ApplManagedWebSecurityFilter implements Filter {
	public static final long time = 1200000;
	public static final Logger logger = LoggerFactory.getLogger(ApplManagedWebSecurityFilter.class);

	public void destroy() {

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		
		arg1.setCharacterEncoding("UTF-8");
		HttpSession session = ((HttpServletRequest) arg0).getSession();
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		PrintWriter out = arg1.getWriter();
        
		session.setMaxInactiveInterval(60*5);
		// session.setMaxInactiveInterval(-1);

		// 获取session对象
		String se = (String) session.getAttribute("username");
		// 获取当前请求的URI
		String url = request.getRequestURI();
logger.info(url);
		if(url.indexOf(".do")>0)
		{
			arg2.doFilter(request, response);
			return;
		}
		if (se == null
				&& (!url.endsWith("login.jsp")) // 对URL地址为此结尾的文件不过滤
				&& url.indexOf("/images/") < 0) {
			// request.getRequestDispatcher("/jsp/login.jsp").forward(arg0,arg1);
			out.println("<script type='text/javascript'>top.window.location='"
					+ request.getContextPath() + "/login.jsp';</script>");
			// out.println("<script type='text/javascript'>if(window.parent==null){window.location='"+request.getContextPath()+"/jsp/login.jsp';}else{parent.window.location='"+request.getContextPath()+"/jsp/login.jsp';}</script>");
		} else {
			arg2.doFilter(request, response);
			response.setHeader("Cache-Control", "no-store");
			response.setDateHeader("Expires", 0);
			response.setHeader("Pragma", "no-cache");
			response.flushBuffer();
		}
		out.close();
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
